import json
import requests

def load_config(config_file):
    """读取配置文件并返回内容"""
    try:
        with open(config_file, 'r') as f:
            return json.load(f)
    except Exception as e:
        print(f"读取配置文件 {config_file} 失败: {e}")
        return []

def get_running_jobs(flink_api_url):
    """获取 Flink 运行中的任务列表"""
    try:
        response = requests.get(flink_api_url)
        response.raise_for_status()
        return response.json().get('jobs', [])
    except requests.RequestException as e:
        print(f"从 {flink_api_url} 获取任务列表失败: {e}")
        return []

def start_job(jar_id, flink_run_url):
    """启动指定 JAR 的任务"""
    try:
        response = requests.post(flink_run_url.format(jar_id=jar_id))
        response.raise_for_status()
        print(f"成功启动 JAR {jar_id} 的任务")
    except requests.RequestException as e:
        print(f"启动 JAR {jar_id} 的任务失败: {e}")

def main():
    config_file = "config.json"
    flink_jobs_url = "http://flink.base:8081/jobs/overview"
    flink_run_url_template = "http://flink.base:8081/jars/{jar_id}/run?entry-class=com.sumztech.underway.datastore.Application&parallelism=1"

    # 加载配置文件并筛选 switch 为 true 的任务
    config = load_config(config_file)
    jobs_to_run = [job for job in config if job.get('switch', False)]

    # 获取运行中的任务列表，仅考虑 state 为 RUNNING 的任务
    running_jobs = get_running_jobs(flink_jobs_url)
    running_job_names = {job['name'] for job in running_jobs if job.get('state') == 'RUNNING'}

    # 检查并启动缺失或非 RUNNING 的任务
    for job in jobs_to_run:
        job_name = job['name']
        jar_id = job['id']
        
        # 检查任务是否在运行列表中且状态为 RUNNING
        if job_name in running_job_names:
            print(f"任务 {job_name} 已运行（状态为 RUNNING）。跳过...")
        else:
            print(f"任务 {job_name} 未运行或不在任务列表中。正在启动 JAR {jar_id}...")
            start_job(jar_id, flink_run_url_template)

if __name__ == "__main__":
    main()